package com.ticket.sass.admin.call;

import com.ticket.sass.admin.business.OrderTicketBusiness;
import com.ticket.sass.admin.business.impl.FilmScheduleBusinessImpl;
import com.ticket.sass.admin.manager.MybatisTenantIgnoreManager;
import com.ticket.sass.admin.service.impl.CinemaServiceImpl;
import com.ticket.sass.common.entity.tenant.CinemaEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ywb
 * @date 2022-03-22 10:22
 */
@Slf4j
@Component
@EnableScheduling
public class DynamicScheduledTask implements SchedulingConfigurer {
    
    @Autowired
    private CinemaServiceImpl cinemaService;
    
    @Autowired
    private FilmScheduleBusinessImpl business;
    
    @Autowired
    private OrderTicketBusiness orderTicketBusiness;
    
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 设置忽略
        MybatisTenantIgnoreManager.INSTANCE.setValue(new MybatisTenantIgnoreManager.IgnoreField(true, true));
        // 获取所有影院的列表
        List<CinemaEntity> cinemaList = cinemaService.list();
        // 恢复默认设置
        MybatisTenantIgnoreManager.INSTANCE.setValue(new MybatisTenantIgnoreManager.IgnoreField(false, false));
        
        // 为每个影院创建一个定时任务
        for (CinemaEntity cinema : cinemaList) {
            Long cinemaId = cinema.getId();
            taskRegistrar.addCronTask(
                () -> {
                    // 设置忽略
                    MybatisTenantIgnoreManager.INSTANCE.setValue(new MybatisTenantIgnoreManager.IgnoreField(true, true));
                    
                    try {
                        // 调用实际的业务逻辑
                        business.refreshSchedule(cinemaId);
                    } finally {
                        // 恢复默认设置
                        MybatisTenantIgnoreManager.INSTANCE.setValue(new MybatisTenantIgnoreManager.IgnoreField(false, false));
                    }
                },
                "0 0/30 * * * ?"
            );
            
            
            taskRegistrar.addCronTask(
                () -> {
                    // 设置忽略
                    MybatisTenantIgnoreManager.INSTANCE.setValue(new MybatisTenantIgnoreManager.IgnoreField(true, true));
                    
                    try {
                        orderTicketBusiness.generateTicketStatistics(cinemaId);
                    } finally {
                        // 恢复默认设置
                        MybatisTenantIgnoreManager.INSTANCE.setValue(new MybatisTenantIgnoreManager.IgnoreField(false, false));
                    }
                },
                "0 0 15 * * ?"
            );
        }
    }
    
}
